// 在store/cart.js中定义购物车store
import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  persist: true,
  state: () => ({
    items: [],
  }),

  getters: {
    // 计算购物车商品总数
    totalCount: (state) => {
      return state.items.reduce((total, item) => total + item.quantity, 0)
    },

    // 计算选中商品的总价
    totalPrice: (state) => {
      return state.items
        .filter((item) => item.selected)
        .reduce((total, item) => {
          // 确保价格是数字
          const price = parseFloat(item.price) || 0
          return total + price * item.quantity
        }, 0)
        .toFixed(2)
    },

    // 计算选中的商品数量
    selectedCount: (state) => {
      return state.items.filter((item) => item.selected).length
    },

    // 检查是否全选
    isAllSelected: (state) => {
      return state.items.length > 0 && state.items.every((item) => item.selected)
    },
  },

  actions: {
    // 添加商品到购物车
    addItem(product) {
      // 确保商品有必要的属性
      const productWithDefaults = {
        selected: true,
        imageLoaded: false,
        imageError: false,
        ...product,
        quantity: product.quantity || 1,
      }

      const existingItem = this.items.find((item) => item.id === productWithDefaults.id)
      if (existingItem) {
        existingItem.quantity += productWithDefaults.quantity
      } else {
        this.items.push(productWithDefaults)
      }
    },

    // 从购物车移除商品
    removeItem(productId) {
      const index = this.items.findIndex((item) => item.id === productId)
      if (index > -1) {
        this.items.splice(index, 1)
      }
    },

    // 更新商品数量
    updateQuantity(productId, quantity) {
      const item = this.items.find((item) => item.id === productId)
      if (item) {
        const newQuantity = parseInt(quantity)
        if (newQuantity <= 0) {
          this.removeItem(productId)
        } else {
          item.quantity = newQuantity
        }
      }
    },

    // 切换商品选中状态
    toggleItemSelection(productId) {
      const item = this.items.find((item) => item.id === productId)
      if (item) {
        item.selected = !item.selected
      }
    },

    // 全选/取消全选
    toggleAllSelection() {
      const newState = !this.isAllSelected
      this.items.forEach((item) => {
        item.selected = newState
      })
    },

    // 清空购物车
    clearCart() {
      this.items = []
    },

    // 清空选中的商品
    clearSelected() {
      this.items = this.items.filter((item) => !item.selected)
    },

    // 初始化购物车商品数据
    initializeItems() {
      // 确保每个商品都有必要的属性
      this.items = this.items.map((item) => ({
        selected: item.selected !== undefined ? item.selected : true,
        imageLoaded: item.imageLoaded || false,
        imageError: item.imageError || false,
        ...item,
        quantity: item.quantity || 1,
      }))
    },
  },

  // 在store初始化时调用
  hydrate(store) {
    // 确保从持久化存储恢复的数据格式正确
    store.initializeItems()
  },
})
